<template>
  <el-tabs type="border-card">
    <el-tab-pane label="商品基本信息">
      {{goodsForm}}
      <el-form ref="form" :model="goodsForm" label-width="80px">
        <el-form-item label="商品分类">
          <!--<el-input v-model="goodsForm.goods.category1Id"></el-input>-->
          <!--商品三级分类：-->
          <!--1. 商品一级分类：-->
          <el-select v-model="goodsForm.goods.category1Id">
            <el-option :label="cate.name" :value="cate.id" v-for="cate in category1List" :key="cate.id"></el-option>
          </el-select>
          <!--2. 商品二级分类：(点击一级分类时自动添加对应的二级分类)-->
          <el-select v-model="goodsForm.goods.category2Id">
            <el-option :label="cate.name" :value="cate.id" v-for="cate in category2List" :key="cate.id"></el-option>
          </el-select>
          <!--3. 商品三级分类：(点击二级分类时自动添加对应的三级分类)-->
          <el-select v-model="goodsForm.goods.category3Id">
            <el-option :label="cate.name" :value="cate.id" v-for="cate in category3List" :key="cate.id"></el-option>
          </el-select>
          模板ID: {{goodsForm.goods.typeTemplateId}}
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="goodsForm.goods.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="商品品牌">
          <!--<el-input v-model="goodsForm.goods.goodsName"></el-input>-->
          <el-select v-model="goodsForm.goods.brandId">
            <el-option :label="brand.text" :value="brand.id" v-for="brand in brandList" :key="brand.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="副标题">
          <el-input v-model="goodsForm.goods.caption"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="goodsForm.goods.price"></el-input>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input type="textarea" v-model="goodsForm.goodsDesc.introduction"></el-input>
        </el-form-item>
        <el-form-item label="包装列表">
          <el-input type="text" v-model="goodsForm.goodsDesc.packageList"></el-input>
        </el-form-item>
        <el-form-item label="售后服务">
          <el-input type="text" v-model="goodsForm.goodsDesc.saleService"></el-input>
        </el-form-item>

      </el-form>
    </el-tab-pane>
    <el-tab-pane label="商品图片">
      <el-button type="primary" plain size="small" @click="newBtnHandler">新建</el-button>
      <el-table
        :data="goodsForm.goodsDesc.itemImages"
        style="width: 100%">
        <el-table-column
          label="颜色"
          align="center"
          prop="color">
        </el-table-column>
        <el-table-column
          align="center"
          label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.url" width="100px"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="goodsForm.goodsDesc.itemImages.splice(scope.$index, 1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="上传商品图片" :visible.sync="dialogFormVisible">
        {{imageEntity}}
        <el-form :model="imageEntity">
          <el-form-item label="颜色" :label-width="formLabelWidth">
            <el-input v-model="imageEntity.color" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品图片" :label-width="formLabelWidth">
            <el-upload
              class="upload-demo"
              action=""
              :file-list="fileList"
              :http-request="uploadFile"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="savePic">确 定</el-button>
        </div>
      </el-dialog>

    </el-tab-pane>
    <el-tab-pane label="扩展属性">
      <el-table
        :data="goodsForm.goodsDesc.customAttributeItems"
        style="width: 100%">
        <el-table-column
          align="center"
          width="180">
          <template slot-scope="scope">
            {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.value"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="规格">
      <el-table
        :data="specList"
        style="width: 100%">
        <el-table-column
          align="center"
          width="180">
          <template slot-scope="scope">
            {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column align="left">
          <template slot-scope="scope">
            <el-checkbox-group v-model="optionList[scope.$index]" size="small" @change="userSelect">
              <el-checkbox :label="option.optionName" border v-for="option in scope.row.options" :key="option.id"></el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>
      </el-table>
      <el-table
        :data="goodsForm.itemList"
        style="width: 100%">
        <el-table-column
          :label="sp.attributeName"
          :key="sp.attributeName"
          v-for="sp in goodsForm.goodsDesc.specificationItems"
          align="center">
          <template slot-scope="scope">
              {{scope.row.spec[sp.attributeName]}}
          </template>
        </el-table-column>
        <el-table-column
          label="价格"
          align="center">
          <template slot-scope="scope">
           <el-input v-model="scope.row.price"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="库存量"
          align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.num"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <div style="margin-top: 20px;">
      <el-button type="success" plain size="small" @click="save">保存</el-button>
      <el-button type="primary" plain size="small">返回列表</el-button>
    </div>

  </el-tabs>


</template>

<script>
  export default {
    data() {
      return {
        goodsForm: {
          goods: {typeTemplateId: '', brandId: '', category1Id: '', category2Id: '', category3Id: ''},
          goodsDesc: {customAttributeItems: [],itemImages:[],specificationItems:[]},
          itemList: []
        },
        category1List: [],     // 一级分类列表
        brandList: [],         // 某个模板对应的品牌列表
        category2List: [],     // 二级分类列表
        category3List: [],     // 三级分类列表
        dialogFormVisible:false,  // 控制图片上传的对话框
        imageEntity:{},        // 当前上传的图片对象
        formLabelWidth:'100px',
        fileList:[],          // 上传后的图片列表
        specList:[],          // 规格及规格选项列表
        optionList:[],        // 匹配规格选项的数组,有多少个规格就有多少个子数组
        specNames:[],         // 匹配规格名称的数组
      }
    },
    // 计算属性简化属性名字
    computed: {
      category1Id() {
        return this.goodsForm.goods.category1Id;
      },
      category2Id() {
        return this.goodsForm.goods.category2Id;
      },
      category3Id() {
        return this.goodsForm.goods.category3Id;
      },
      typeTemplateId() {
        return this.goodsForm.goods.typeTemplateId;
      }
    },
    // 使用watch进行变量值的监听
    watch: {
      //1. 一级分类变化查询出对应的二级分类列表
      category1Id(newV, oldV) { //此时的newV就是一级分类的id
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${newV}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data:", data)
            this.category2List = data.itemCatList
            if(!this.$route.query.id){
              delete this.goodsForm.goods.category2Id
              delete this.goodsForm.goods.category3Id
            }

          }
        })
      },
      //2. 二级分类变化查询出三级分类列表
      category2Id(newV, oldV) {
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${newV}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data:", data)
            this.category3List = data.itemCatList
            if(!this.$route.query.id){
              delete this.goodsForm.goods.category3Id
            }

          }
        })
      },
      //3. 三级分类id发生变化时，查询出分类对象关联的模板id并赋值给: goodsForm.goods.typeTemplateId
      category3Id(newV, oldV) {
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/info/${newV}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.goodsForm.goods.typeTemplateId = data.itemCat.typeId

          }
        })
      },
      //4. 当模板id发生变化时，
      //4.1 查询出此模板对应的品牌列表并展示
      typeTemplateId(newV, oldV) {
        this.$http({
          url: this.$http.adornUrl(`/shop/typetemplate/info/${newV}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data:", data)
            // ① 查询出模板关联的品牌列表
            this.brandList = JSON.parse(data.typeTemplate.brandIds)
            // ② 查询出模板关联的自定义扩展属性列表
            if(!this.$route.query.id){
              this.goodsForm.goodsDesc.customAttributeItems = JSON.parse(data.typeTemplate.customAttributeItems)
            }

            // ③ 根据模板查询出规格及规格选项列表
            this.$http({
              url: this.$http.adornUrl(`/shop/typetemplate/findSpecAndOptions/${newV}`),
              method: 'get'
            }).then(({data}) => {
              if (data && data.code === 0) {
                console.log("data-spec:", data)
                this.specList = data.spec
                data.spec.forEach(sp=>{
                  this.optionList.push([])
                  this.specNames.push(sp.text)
                })

              }
            })
          }
        })
      }

    },
    activated() {
      //1. 查询一级分类
      this.findCategory1List(0)
      //2. 根据id查询商品信息
      this.findById()
    },
    methods: {
      findById(){
        //1. 得到要修改的商品的id
        let id = this.$route.query.id
        this.$http({
          url: this.$http.adornUrl(`/shop/goods/findById/${id}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data:", data)
            this.goodsForm = data.goods
            //处理数据
            this.goodsForm.goods.brandId = parseInt(this.goodsForm.goods.brandId)
            this.goodsForm.goodsDesc.itemImages = JSON.parse( this.goodsForm.goodsDesc.itemImages)
            this.goodsForm.goodsDesc.customAttributeItems = JSON.parse(this.goodsForm.goodsDesc.customAttributeItems)
            this.goodsForm.goodsDesc.specificationItems = JSON.parse(this.goodsForm.goodsDesc.specificationItems)
            this.goodsForm.itemList.forEach(item=>{
              item.spec = JSON.parse(item.spec)
            })
            //optionList这个数组赋值
            this.goodsForm.goodsDesc.specificationItems.forEach(spec=>{
              let attValue = spec.attributeValue
              this.optionList.push(attValue)
            })
          }
        })
      },
      //0. 点击了新建按钮
      newBtnHandler(){
        this.dialogFormVisible = true
        this.fileList = []
        this.imageEntity = {}
      },
      //1. 完成文件上传
      uploadFile(v){
        //1.1 借助h5的formData完成文件上传
        let data = new FormData();
        data.append("file",v.file);
        //1.2 准备开始文件上传
        this.$http({
          url: this.$http.adornUrl(`/thirdparty/upload`),
          method: 'post',
          header:{'Content-Type':'multipart/form-data'},
          data
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data-upload:",data)
            this.imageEntity.url = data.url
          }
        })
      },
      //保存图片
      savePic(){
        // 关闭对话框
        this.dialogFormVisible = false;
        // 将上传的图片放到图片列表中
        this.goodsForm.goodsDesc.itemImages.push(this.imageEntity)
      },
      // 用户选择
      userSelect(){
        //第一部分： 完成用户点击后为goodsForm.goodsDesc.specificationItems字段赋值
        // console.log("userSelect:",this.optionList)
        // console.log("specName:",specName)
        // console.log("specNames:",this.specNames)
        // ① 定义一个数组
        let specs = [];
        // ② 遍历this.optionList数组，得到其中的每一项
        for (let i = 0; i < this.specNames.length; i++) {
           //1. 得到规格名字
           let specName = this.specNames[i]
           //2. 得到这个规格名字对应的规格选项（当前用户选择的）
          let options = this.optionList[i]
           //3. 将其添加到specs这个新数组中
          specs.push({"attributeName":specName,"attributeValue":options})
        }
        //将当前的数组specs设置给specificationItems属性
        this.goodsForm.goodsDesc.specificationItems = specs.filter(f=>f.attributeValue.length > 0);

        //第二部分：为sku商品列表itemList赋值
        this.createItemList()
      },
      // 动态生成sku商品列表
      createItemList(){
        //1. 为itemList赋初始值
        this.goodsForm.itemList = [{spec:{},num:999,price:10,status:0,isDefault: 0}]
        //2. 得到用户选择的规格及规格选项
        let specItems = this.goodsForm.goodsDesc.specificationItems
        //3. 为sku商品列表赋值
        specItems.forEach(spec=>{
          this.goodsForm.itemList = this.addColumn(this.goodsForm.itemList,spec.attributeName,spec.attributeValue)
        })
      },
      addColumn(itemList,attributeName,attributeValue){
        //1. 定义一个空数组
        let sku = []
        //2. 遍历为空数组赋值
        itemList.forEach(item=>{
          attributeValue.forEach(attr=>{
            //2.1 得到原来的空行并进行深克隆
            let newRow = JSON.parse(JSON.stringify(item))
            //2.2 为新对象赋值
            newRow.spec[attributeName] = attr
            //2.3 将新行的数据放到sku数组中
            sku.push(newRow)
          })
        })
        return sku;
      },
      //1. 查询一级分类
      findCategory1List(parentId) {
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${parentId}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data:", data)
            this.category1List = data.itemCatList
          }
        })
      },

      // 保存商品
      save(){
        //1. 处理数据
        this.goodsForm.goodsDesc.specificationItems = JSON.stringify(this.goodsForm.goodsDesc.specificationItems )
        this.goodsForm.goodsDesc.itemImages = JSON.stringify(this.goodsForm.goodsDesc.itemImages )
        this.goodsForm.goodsDesc.customAttributeItems = JSON.stringify( this.goodsForm.goodsDesc.customAttributeItems)
        this.goodsForm.itemList.forEach(item=>{
          item.spec = JSON.stringify(item.spec)
        })
        this.$http({
          url: this.$http.adornUrl(`/shop/goods/${this.goodsForm.goods.id ? 'update' : 'save'}`),
          method: `${this.goodsForm.goods.id ? 'PUT' : 'POSt'}`,
          data: this.goodsForm
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data:", data)
            this.goodsForm = {
              goods: {typeTemplateId: '', brandId: '', category1Id: '', category2Id: '', category3Id: ''},
              goodsDesc: {customAttributeItems: [],itemImages:[],specificationItems:[]},
              itemList: []
            }
          }
        })
      }
    }
  }
</script>
